import AV, {User, Query} from 'leancloud-storage';

AV.init({
    appId: 'Fehj7iv2xQ208ay3U8Fg2q8v-gzGzoHsz',
    appKey: 'Fa8NRMDkMMxOQPC7dUHf52OB',
    serverURL: 'https://fehj7iv2.lc-cn-n1-shared.com'
});

const Auth = {
    register(username: string, password: string) {
        let user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return new Promise((resolve, reject) => {
            user.signUp().then(loginedUser => resolve(loginedUser), error => reject(error));
        });
    },

    login(username: string, password: string) {
        return new Promise((resolve, reject) => {
            User.logIn(username, password).then(loginedUser => resolve(loginedUser), error => reject(error));
        })
    },

    logout() {
        return User.logOut()
    },

    getCurrentUser() {
        return User.current()
    }
};


const Uploader = {
    add(file: any, filename: string) {
        const item = new AV.Object('Image');
        const avFile = new AV.File(filename, file);
        item.set('filename', filename);
        item.set('owner', AV.User.current())
        item.set('url', avFile);
        console.log(item)
        return new Promise((resolve, reject) => {
            item.save().then(serverFile => {
                console.log('保存成功');
                resolve(serverFile)
            }, error => {
                console.log('保存失败');
                reject(error)
            })
        })
    },
    find({page=0, limit=10}) {
        const query = new AV.Query('Image');
        query.include('owner');
        query.limit(limit);
        query.skip(page * limit);
        query.equalTo('owner', AV.User.current())
        console.log(AV.User.current())
        return new Promise((resolve, reject) => {
            query.find()
                .then(results => {
                    resolve(results)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }

}


export {Auth, Uploader}
